#!/usr/bin/env node

/** 菜单同步工具 将数据库中的菜单数据同步到前端路由配置 */

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import process from 'node:process';

const filename = fileURLToPath(import.meta.url);
const dirname = path.dirname(filename);

// 模拟从数据库获取的菜单数据
const mockMenuData = [
  {
    id: 1,
    menuName: '系统管理',
    routeName: 'manage',
    routePath: '/manage',
    component: null,
    icon: 'carbon:cloud-service-management',
    menuType: '1',
    parentId: 0,
    orderNum: 1,
    status: '1',
    children: [
      {
        id: 2,
        menuName: '用户管理',
        routeName: 'manage_user',
        routePath: '/manage/user',
        component: 'views/manage/user/index.vue',
        icon: 'carbon:user',
        menuType: '2',
        parentId: 1,
        orderNum: 1,
        status: '1'
      },
      {
        id: 3,
        menuName: '角色管理',
        routeName: 'manage_role',
        routePath: '/manage/role',
        component: 'views/manage/role/index.vue',
        icon: 'carbon:user-role',
        menuType: '2',
        parentId: 1,
        orderNum: 2,
        status: '1'
      },
      {
        id: 4,
        menuName: '菜单管理',
        routeName: 'manage_menu',
        routePath: '/manage/menu',
        component: 'views/manage/menu/index.vue',
        icon: 'carbon:menu',
        menuType: '2',
        parentId: 1,
        orderNum: 3,
        status: '1'
      }
    ]
  },
  {
    id: 5,
    menuName: '功能演示',
    routeName: 'function',
    routePath: '/function',
    component: null,
    icon: 'carbon:function',
    menuType: '1',
    parentId: 0,
    orderNum: 2,
    status: '1',
    children: [
      {
        id: 6,
        menuName: '多标签页',
        routeName: 'function_multi-tab',
        routePath: '/function/multi-tab',
        component: 'views/function/multi-tab/index.vue',
        icon: 'carbon:tab',
        menuType: '2',
        parentId: 5,
        orderNum: 1,
        status: '1'
      },
      {
        id: 7,
        menuName: '标签页',
        routeName: 'function_tab',
        routePath: '/function/tab',
        component: 'views/function/tab/index.vue',
        icon: 'carbon:tab-desktop',
        menuType: '2',
        parentId: 5,
        orderNum: 2,
        status: '1'
      }
    ]
  }
];

/** 生成路由配置 */
function generateRouteConfig(menus) {
  const routes = menus
    .filter(menu => menu.status === '1')
    .map(menu => {
      const route = {
        name: menu.routeName,
        path: menu.routePath,
        meta: {
          title: menu.menuName,
          i18nKey: `route.${menu.routeName}`,
          icon: menu.icon,
          order: menu.orderNum
        }
      };

      // 如果有组件，添加组件配置
      if (menu.component) {
        route.component = menu.component;
      }

      // 如果有子菜单，递归处理
      if (menu.children && menu.children.length > 0) {
        route.children = generateRouteConfig(menu.children);
      }

      return route;
    })
    .sort((a, b) => (a.meta.order || 0) - (b.meta.order || 0));

  return routes;
}

/** 生成菜单配置 */
function generateMenuConfig(menus) {
  const menuConfig = menus
    .filter(menu => menu.status === '1')
    .map(menu => {
      const menuItem = {
        key: menu.routeName,
        label: menu.menuName,
        i18nKey: `route.${menu.routeName}`,
        routeKey: menu.routeName,
        routePath: menu.routePath,
        icon: menu.icon,
        order: menu.orderNum
      };

      // 如果有子菜单，递归处理
      if (menu.children && menu.children.length > 0) {
        menuItem.children = generateMenuConfig(menu.children);
      }

      return menuItem;
    })
    .sort((a, b) => (a.order || 0) - (b.order || 0));

  return menuConfig;
}

/** 生成国际化配置 */
function generateI18nConfig(menus) {
  const i18nKeys = new Set();

  function collectI18nKeys(menuList) {
    menuList.forEach(menu => {
      if (menu.routeName) {
        i18nKeys.add(`route.${menu.routeName}`);
      }
      if (menu.children && menu.children.length > 0) {
        collectI18nKeys(menu.children);
      }
    });
  }

  collectI18nKeys(menus);

  const i18nConfig = {};
  Array.from(i18nKeys).forEach(key => {
    const routeName = key.replace('route.', '');
    i18nConfig[key] = routeName.replace(/_/g, ' ');
  });

  return i18nConfig;
}

/** 主函数 */
function main() {
  console.log('🚀 开始同步菜单数据...');

  try {
    // 生成路由配置
    const routes = generateRouteConfig(mockMenuData);
    const routesContent = `// 自动生成的路由配置 - 请勿手动修改
export const menuRoutes = ${JSON.stringify(routes, null, 2)};
`;

    // 生成菜单配置
    const menus = generateMenuConfig(mockMenuData);
    const menusContent = `// 自动生成的菜单配置 - 请勿手动修改
export const menuConfig = ${JSON.stringify(menus, null, 2)};
`;

    // 生成国际化配置
    const i18nConfig = generateI18nConfig(mockMenuData);
    const i18nContent = `// 自动生成的国际化配置 - 请勿手动修改
export const menuI18n = ${JSON.stringify(i18nConfig, null, 2)};
`;

    // 写入文件
    const outputDir = path.join(dirname, '../src/config');
    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir, { recursive: true });
    }

    fs.writeFileSync(path.join(outputDir, 'menu-routes.ts'), routesContent);
    fs.writeFileSync(path.join(outputDir, 'menu-config.ts'), menusContent);
    fs.writeFileSync(path.join(outputDir, 'menu-i18n.ts'), i18nContent);

    console.log('✅ 菜单同步完成！');
    console.log('📁 生成的文件：');
    console.log('  - src/config/menu-routes.ts');
    console.log('  - src/config/menu-config.ts');
    console.log('  - src/config/menu-i18n.ts');
    console.log('');
    console.log('💡 使用说明：');
    console.log('  1. 在路由配置中导入 menuRoutes');
    console.log('  2. 在菜单组件中导入 menuConfig');
    console.log('  3. 在国际化文件中导入 menuI18n');
    console.log('');
    console.log('🔄 下次运行：npm run sync-menu');
  } catch (error) {
    console.error('❌ 菜单同步失败：', error.message);
    process.exit(1);
  }
}

// 如果直接运行此脚本
main();
